/************************
Name : TestCaseManagerController
Created By : knemala
Created Date : Feb 25, 2013
Description : This is a TEST class, to cover CaseManagerController.

************************/
@isTest
private class TestCaseManagerController {
    private static CaseManagerController initialize(){
        CaseManagerController controller = new CaseManagerController();
        controller.strSelectedSearchOptionForQueueTab = controller.strSelectedSearchOptionForUserTab = controller.listSelectOptionSearchOptions != NULL && controller.listSelectOptionSearchOptions.size() > 0 ?controller.listSelectOptionSearchOptions.get(0).getValue() : 'FirstName'; 
        return controller;
    }
    
    private static list<Group> getQueues(){
        list<Group> listExistingGroups = new list<Group>();
        try{
            list<QueueSobject> lstQueueDetails = [Select QueueId, Queue.Name from QueueSobject where SobjectType='Case' and Queue.Name Like '%CM - %'];
            Set<Id> setQueueIds = new Set<Id>();
            for(QueueSobject loopQueue :lstQueueDetails ){
                setQueueIds.add(loopQueue.QueueId);
            }
            listExistingGroups = [Select Id, Name from Group where Id in :setQueueIds];
        }
        Catch(Exception e){
            
        }
    return listExistingGroups;
    }
    
    static testMethod void queueTabChangingQueue(){
        String testQueue = 'KKK';
        CaseManagerController controller = initialize();
        list<Group> listExistingGroups = getQueues();
        
         list<Apexpages.Message> listApexPageMessages;
         ApexPages.Message currentApexMessage;
        
        /* selecting a Queue that does not exist */
        controller.strSelectedQueues = testQueue;
        controller.updateUsersInMultiSelectListBasedOnQueue();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'Only the first 100 Available Users are displayed. Please refine your search criteria');
        System.debug('Message is' +currentApexMessage.getSummary());
        System.debug('Test is '+listApexPageMessages.get(0).getSummary());
        //system.assert(listApexPageMessages.size()==1 && listApexPageMessages.get(0).getSummary().equals(currentApexMessage.getSummary()) ,'No Such Queue');
        System.assertEquals(currentApexMessage.getSummary(),listApexPageMessages.get(0).getSummary() );
        /*Selecting a valid Queue and empty Search key*/
        controller.strSearchKeyForQueue = '';
        String strTestQueueName = 'CM - Queue 21';
         if(controller.listSelOptQueues!= NULL && controller.listSelOptQueues.size()>=2){
          strTestQueueName = controller.listSelOptQueues.get(1).getValue();
          }
        controller.strSelectedQueues = strTestQueueName;
      //  Test.startTest();
        controller.updateUsersInMultiSelectListBasedOnQueue();
       // Test.stopTest();
        
        /*Change to Queue - 'None'*/
        try{
            User usrTest = new User(FirstName='Code', LastName='Test', Alias='CTest', Email='CodeCoverage@test.com', UserName='CodeCoverage@test.com', ProfileID=[Select Id from Profile where Name='System Administrator'].Id, TimeZoneSidKey = 'America/Phoenix', LocaleSidKey = 'en_US', LanguageLocaleKey = 'en_US' ,EmailEncodingKey = 'UTF-8');
            insert usrTest;
            controller.strSearchKeyForQueue = usrTest.FirstName;        
        }
        Catch(Exception e){
            System.debug('Exception: ' +e);
        }
        controller.updateUsersInMultiSelectListBasedOnQueue();
        controller.strSelectedQueues='';
        controller.updateUsersInMultiSelectListBasedOnQueue();
        system.assert(controller.listSelOptUsersAvailableForSelection != NULL && controller.listSelOptUsersAvailableForSelection.size()==0,'listSelOptUsersAvailableForSelection not cleared');
    }
    
    static testMethod void queueTabFindTest(){
        CaseManagerController controller = initialize();
        list<Apexpages.Message> listApexPageMessages;
        ApexPages.Message currentApexMessage;
        controller.findUsers();
         listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,' Please Select a Queue');
        system.debug('\n listApexPageMessages: '+listApexPageMessages + '\n listApexPageMessages.size(): '+ listApexPageMessages.size() + '\n currentApexMessage.getSummary(): '+currentApexMessage.getSummary());
        system.assert(listApexPageMessages.size()==1 && listApexPageMessages.get(0).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting error message: Please Select a Queue');
        
        list<Group> listGrpExistingGroups = getQueues();
        String strTestQueueName = 'CM - Queue 1';
         if(controller.listSelOptQueues!= NULL && controller.listSelOptQueues.size()>=2)
          strTestQueueName = controller.listSelOptQueues.get(1).getValue();
         controller.strSelectedQueues = strTestQueueName;
         controller.updateUsersInMultiSelectListBasedOnQueue();
        listApexPageMessages = ApexPages.getMessages();
        system.debug('\n listApexPageMessages: '+listApexPageMessages + '\n listApexPageMessages.size(): '+ listApexPageMessages.size());
        system.assert(listApexPageMessages.size()==2,' Please select a Queue');
        
        controller.strSearchKeyForQueue = '';
        controller.findUsers();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.ERROR,' Please Enter the search content');
        system.debug('\n listApexPageMessages: '+listApexPageMessages + '\n listApexPageMessages.size(): '+ listApexPageMessages.size() + '\n currentApexMessage.getSummary(): '+currentApexMessage.getSummary());
        system.assert(listApexPageMessages.size()==3 && listApexPageMessages.get(2).getSummary().contains(currentApexMessage.getSummary()) ,'Expecting error message: Please Enter the search content');
     
        /* with search text and no such user */
        controller.strSelectedSearchOptionForQueueTab = controller.listSelectOptionSearchOptions != NULL && controller.listSelectOptionSearchOptions.size()>1 ? controller.listSelectOptionSearchOptions.get(1).getValue() : 'LastName';
        controller.strSearchKeyForQueue = 'adasdsdadsadasda';
        controller.findUsers();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'User ' +controller.strSearchKeyForQueue  +' is already in the Queue or does not exist');
        system.debug('\n listApexPageMessages: '+listApexPageMessages + '\n listApexPageMessages.size(): '+ listApexPageMessages.size() + '\n currentApexMessage.getSummary(): '+currentApexMessage.getSummary());
       // system.assert(listApexPageMessages.size()==4 && listApexPageMessages.get(3).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting error message: User ' +controller.strSearchKeyForQueue +' is already in the Queue or does not exist');
       System.debug('============================>' +currentApexMessage.getSummary());
       System.debug('============================>' +listApexPageMessages.get(3).getSummary());
       System.assertEquals(currentApexMessage.getSummary(),listApexPageMessages.get(3).getSummary() );
        // find users after entering search text
        try{
          User usrTest = new User(FirstName='Code', LastName='Test', Alias='CTest', Email='CodeCoverage@test.com', UserName='CodeCoverage@test.com', ProfileID=[Select Id from Profile where Name='System Administrator'].Id, TimeZoneSidKey = 'America/Phoenix', LocaleSidKey = 'en_US', LanguageLocaleKey = 'en_US' ,EmailEncodingKey = 'UTF-8');
            insert usrTest;
          controller.strSearchKeyForQueue = usrTest.FirstName;// Set the Search Text
        }Catch(Exception E){
            system.debug('Exception: '+E);
          }
     //   Test.startTest();
        controller.findUsers();// call find method
        //Test.stopTest();
    }
    
    static testMethod void queueTabSave(){
        CaseManagerController controller = initialize();
        list<Apexpages.Message> listApexPageMessages;
        ApexPages.Message currentApexMessage;
        
        /*No queue selected*/
         controller.modifyUsersInQueue();
         
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'Please Select a Queue');
        system.assert(listApexPageMessages.size()==1 && listApexPageMessages.get(0).getSummary().equals(currentApexMessage.getSummary()) ,'');
        
        /* Adding user to the Queue */
        User usrTestToGroup = new User(FirstName='Code', LastName='Test', Alias='CTest', Email='CodeCoverage@test.com', UserRoleId=[Select Id from UserRole where RollupDescription='West Administration'].Id, UserName='CodeCoverage@test.com', ProfileID=[Select Id from Profile where Name='System Administrator'].Id, TimeZoneSidKey = 'America/Phoenix', LocaleSidKey = 'en_US', Time_Zone_Adjusted__c = true, LanguageLocaleKey = 'en_US' ,EmailEncodingKey = 'UTF-8');
        insert usrTestToGroup; //'00EE0000000Wr34MAC'
        String strTestQueueName = 'CM - Queue 1';
        if(controller.listSelOptQueues!= NULL && controller.listSelOptQueues.size()>=2){    
            strTestQueueName = controller.listSelOptQueues.get(1).getValue();
        }
         try{
          GroupMember grpMem = new GroupMember(UserOrGroupId=usrTestToGroup.id, GroupId=strTestQueueName);
          insert grpMem;
          }Catch(Exception E){
            system.debug('Exception: '+E);
          }
        controller.strSelectedQueues = strTestQueueName;
        controller.updateUsersInMultiSelectListBasedOnQueue();
        controller.modifyUsersInQueue();
        system.debug(controller.listSelOptSelectedUsers);
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'No Changes made');
        system.debug('\n listApexPageMessages: '+listApexPageMessages + '\n listApexPageMessages.size(): '+ listApexPageMessages.size() + '\n currentApexMessage.getSummary(): '+currentApexMessage.getSummary());
        system.assert(listApexPageMessages.size()==3 && listApexPageMessages.get(2).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting message: No Changes made');
       // Making changes to the group and saving
        list<SelectOption> listSelOptTemp = new list<SelectOption>();
        try{
        User usrTestSave = new User(FirstName='Code', LastName='Test', Alias='CTest', Email='CodeCoverage@test.com', UserRoleId=[Select Id from UserRole where RollupDescription='West Case Manager'].Id, UserName='CodeCoverage@test.com', ProfileID=[Select Id from Profile where Name='System Administrator'].Id, TimeZoneSidKey = 'America/Phoenix', LocaleSidKey = 'en_US', Time_Zone_Adjusted__c = true, LanguageLocaleKey = 'en_US' ,EmailEncodingKey = 'UTF-8');
        insert usrTestSave; 
         listSelOptTemp.add(new SelectOption(usrTestSave.id, usrTestSave.FirstName + ' ' + usrTestSave.LastName));
        }
        Catch(Exception E){
          system.debug('Exception: '+E);
        }
        controller.listSelOptSelectedUsers = listSelOptTemp;
     //   Test.startTest();
        controller.modifyUsersInQueue();
      //  Test.stopTest();
        system.assertEquals(listSelOptTemp,controller.listSelOptSelectedUsers,'');
         listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.message(ApexPages.severity.INFO, ' User Queue is modified');
        system.debug(ApexPages.getMessages());
        listApexPageMessages.get(0).getSummary().contains(currentApexMessage.getSummary());
      //  system.assert(listApexPageMessages.size()==5 && listApexPageMessages.get(4).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting Message: User Queue is modified');
        string strCancelRedirectPage = controller.redirectToConsoleHome().getUrl();
        system.assertEquals('/apex/ConsoleHome_VF', strCancelRedirectPage);
        List<String> newUserList;
        List<String> oldUserList;
        List<User> listUsrTempAddedusers = controller.getAddedUsers(newUserList, oldUserList);
        system.assert(listUsrTempAddedusers == NULL);   
    }
    
    static testMethod void userTabFindTest(){
        CaseManagerController controller = initialize();
        controller.findQueues();
        list<Apexpages.Message> listApexPageMessages;
        ApexPages.Message currentApexMessage;
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.ERROR,'Please Enter a search Text');
        system.assert(listApexPageMessages.size()==1 && listApexPageMessages.get(0).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting message: Please Enter a search Text');
        
         controller.strSearchKeyForUser = 'dfgdfgfdghfgh';
        controller.findQueues();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'No users found');
        system.assert(listApexPageMessages.size()==2 && listApexPageMessages.get(1).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting message: No users found');
        // find w a matching search key
        User usrForTest = new User(FirstName='Code', LastName='Test', Alias='CTest', Email='CodeCoverage@test.com', UserRoleId=[Select Id from UserRole where RollupDescription='West Administration'].Id, UserName='CodeCoverage@test.com', ProfileID=[Select Id from Profile where Name='System Administrator'].Id, TimeZoneSidKey = 'America/Phoenix', LocaleSidKey = 'en_US', Time_Zone_Adjusted__c = true, LanguageLocaleKey = 'en_US' ,EmailEncodingKey = 'UTF-8');
         try{
          insert usrForTest;
        }
        catch(Exception E){ 
        }
        controller.strSearchKeyForUser = usrForTest.FirstName;
     //   Test.startTest();
        controller.findQueues();
      //  Test.stopTest();
        system.assertEquals(controller.strIdOfSelectedUser, usrForTest.id,'Found the wrong user');
        controller.strIdOfSelectedUser = usrForTest.id;
        controller.clearValuesforUserTab();
        system.assert(controller.strSearchKeyForQueue =='','did not clear values');
    }
    
    @isTest(seeAllData=true)
    static void userTabSaveTest(){
        // insert test user
        User usrForTest = new User(FirstName='Code', LastName='Test', Alias='CTest', Email='CodeCoverage@test.com', UserRoleId=[Select Id from UserRole where RollupDescription='West Administration'].Id, UserName='CodeCoverage@test.com', ProfileID=[Select Id from Profile where Name='System Administrator'].Id, TimeZoneSidKey = 'America/Phoenix', LocaleSidKey = 'en_US', Time_Zone_Adjusted__c = true, LanguageLocaleKey = 'en_US' ,EmailEncodingKey = 'UTF-8');
         try{
          insert usrForTest;
        }
        catch(Exception E){
          
        }
        list<Apexpages.Message> listApexPageMessages;
        ApexPages.Message currentApexMessage;
         List<Group> listGrpExistingGroups = getQueues();
        list<GroupMember> listGrpMemTestGroupMemberships = new list<GroupMember>();
         for(integer i=0; listGrpExistingGroups != NULL && i<listGrpExistingGroups.size() && i<=1; i++){
          listGrpMemTestGroupMemberships.add(new GroupMember(GroupId = listGrpExistingGroups.get(i).id, UserOrGroupId = usrForTest.id));
        }
        try{
        insert listGrpMemTestGroupMemberships;
        }
        catch(Exception E){
          
        }
        CaseManagerController controller = initialize();
        controller.modifyQueues();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'Please enter Search Text');
        system.assert(listApexPageMessages.size()==1 && listApexPageMessages.get(0).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting message: Please Enter a search Text');
        
        controller.strSelectedSearchOptionForUserTab = 'UserName';
        controller.strSearchKeyForUser = usrForTest.Username;
        controller.findQueues();
        controller.modifyQueues();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'Content Not Modified');
        system.assert(listApexPageMessages.size()==2 && listApexPageMessages.get(1).getSummary().equals(currentApexMessage.getSummary()) ,'Expecting message: Content Not Modified');
        
         list<SelectOption> listSelOptTemp = new list<SelectOption>();
        for(Group loopGrp: listGrpExistingGroups)
          if(listGrpExistingGroups.size()>0 && loopGrp != listGrpExistingGroups.get(0))
            listSelOptTemp.add(new SelectOption(loopGrp.id,loopGrp.Name));
        controller.listSelectOptionGroupsMultiSelectRight = listSelOptTemp.clone();
      //  Test.startTest();
        controller.modifyQueues();
       // Test.stopTest();
        listApexPageMessages = ApexPages.getMessages();
        currentApexMessage = new ApexPages.Message(ApexPages.severity.INFO,'Queues have been modified');
        system.assert(listApexPageMessages.size()==3 && listApexPageMessages.get(2).getSummary().contains(currentApexMessage.getSummary()) ,'Expecting message: Queues have been modified');
     
    }
}